/*
 * @Author: sunzhijun 
 * @Date: 2019-04-18 15:24:35 
 * @Last Modified by: sunzhijun
 * @Last Modified time: 2019-12-25 17:59:59
 */
import CommonAction from './common';
import { base, promptBox } from 'nc-lightapp-front';
import nodeRefs from '../container/functions/nodeRefs';
import deepCopy from 'src/hrpub/common/utils/deep-copy';
import {saveValidate} from "../../../../hrpub/common/utils/utils";
const { NCScrollElement } = base;
export default class CardAction extends CommonAction {
    constructor(comp) {
        super();
        this.comp = comp;
        this.dispatch = this.comp.props.dispatch;
        this.formrelationArr = ['hi_psnorg_h', 'hi_psnjob_h'];
    }

    //卡片页保存数据和顺序调整保存
    saveDataAction = async (type)=>{
        const { props } = this.comp;
        const { main } = props;
        if(main.isSort){
            this.saveAdjustSortAction();
        }else{
            if(type === 'newAdd'){
                await this.dispatch({
                    type: 'main/update',
                    payload: {
                        isNewAdd: true
                    }
                })
            }
            this.saveCheckData();
        }
    }
    //保存顺序调整
    saveAdjustSortAction = async ()=> {
        const { props, action } = this.comp;
        const { editTable, main } = props;
        const { language } = main;
        let allData = editTable.getAllRows(main.tableId);
        let pk_psnjobArr = [];
        let obj = {}, str;
        !!allData.length && allData.map((item, index)=>{
            obj = {
                pk_psnjob: item.values.pk_psnjob.value,
                showorder: item.values.showorder.value
            }
            pk_psnjobArr.push(obj);
        })
        str = JSON.stringify(pk_psnjobArr);
        let res = await this.dispatch({
            type: 'main/saveAdjustSortAction',
            payload: {
                param_json: str,
                pk_org: main.pk_org
            }
        })
        if( res.success ){
            this.toast({color: 'success', content: language['hi6007-000000']});
            action.headerAct.cancelAdjustSort();
            action.tableAct.getMainTableData();
        }
        
    }
    //保存卡片修改数据前校验
    saveCheckData = async () => {
        const {props, action} = this.comp;
        const {dispatch, form, cardTable, button, main, meta} = props;
        const {language, appConfig, pageInfo, areaCodeList, imageData, pk_org, ui_state, pk_psncl, InJobType, hi_psnjob_h, hi_psnorg_h} = main;

        let bd_psndocData = form.getAllFormValue('bd_psndoc');
        let hi_psnjobData = cardTable.getAllData('hi_psnjob');
        console.log('hi_psnjobData', hi_psnjobData)
        if( !hi_psnjobData.rows.length ){
            this.toast({color: 'danger', content: language['hi6007-000288']});
            return;
        }
        // let hi_psndoc_certData = cardTable.getAllData('hi_psndoc_cert');
        let allTableData = {};
        let gridrelation = {};
        areaCodeList.map((item, index) =>{
            if(!main.formLists.includes(item)){ //排除form 
                let tableData = cardTable.getAllRows(item);
                if(tableData.length > 0) {
                    allTableData[item] = {
                        areacode: item,
                        rows: tableData
                    }
                }
                gridrelation[item] = {  
                    srcAreaCode: item,
                    tabRelation: [item]
                }
            }
        })
        meta.getMeta().gridrelation = gridrelation; //此处是因为cardTable.checkTableRequired校验会根据gridrelation判断，如果不替换会有报错。
        // let gridrelation = props.meta.getMeta();
        // delete gridrelation['poi_list'];
        
        for (let key of areaCodeList) {
            if(!main.formLists.includes(key)){ //排除form
                if(!cardTable.checkTableRequired(key)){
                    return false;
                }
            }else{
                if(!form.isCheckNow(key)){
                    return false;
                }
            }
        }
        await saveValidate(
            props,
            '600710C0p',
            'bd_psndoc',
            [],
            'form',
            null,
            null
        );

        for (let tableId of areaCodeList) {
            if(!main.formLists.includes(tableId)){ //排除form
                await saveValidate(
                    props,
                    '600710C0p',
                    tableId,
                    [],
                    'grid',
                    'cardTable',
                    null
                );
            }
        }
        let paramsObj = {
            CurrentPkPsndoc: pk_psncl,             //人员主键
            InJobType: InJobType || 'hire',        //入职类型
            func_type: 5,                               //节点标志
            bd_psndoc: bd_psndocData,                   //人员基本信息卡片
            // hi_psnjob: hi_psnjobData,                //业务关系
            pk_org: pk_org,                        //人力资源组织主键
            ui_state: ui_state,                    //操作状态 1:新增 2:修改
            // hi_psndoc_cert: hi_psndoc_certData,      //身份证件
            hi_psnjob_h: hi_psnjob_h,              //人员工作信息卡片
            hi_psnorg_h: hi_psnorg_h,              //人员组织关系卡片
            image: imageData,
            ...allTableData
        }
        console.log("参数啊参数",paramsObj);
        let res = await dispatch({
            type: 'main/saveCheckData',
            payload: {
                ...paramsObj
            }
        });
        if (res.success) {
            let data = res.data;
            let confirmArr = [];
            let isSure = true;
            if(data.errMsg){
                this.toast({color: 'danger', content: data.errMsg});
            }else{
                if(!!data.worningMsg.length){
                    promptBox({
                        color: 'warning',
                        title: '',
                        noCancelBtn: false,
                        content: (
                            <div 
                                dangerouslySetInnerHTML={{
                                    __html: data.worningMsg[0]
                                }}
                            ></div> // 
                        ),
                        beSureBtnClick: () => {
                            isSure = false;
                            if(!!data.confirmMsg.length){
                                this.showPromptBox(data.confirmMsg[0], paramsObj);
                            }else{
                                this.saveData(paramsObj);
                            }
                        }
                    });
                }else{
                    if(isSure){
                        if(!!data.confirmMsg.length){
                            this.showPromptBox(data.confirmMsg[0], paramsObj);
                        }else{
                            this.saveData(paramsObj);
                        }
                    }
                }
            }
        }
    }

    // 显示promptBox
    showPromptBox = (msg, paramsObj)=>{
        promptBox({
            color: 'warning',
            title: '',
            content: (
                <div 
                    dangerouslySetInnerHTML={{
                        __html: msg
                    }}
                ></div>
            ),
            beSureBtnClick: () => {
                this.saveData(paramsObj);
            }
        });
    }

    //保存新增的数据
    saveData = async (paramsObj)=>{
        const {action, props} = this.comp;
        const {form, cardTable, main } = props;
        const { language } = main;
        let res = await this.dispatch({
            type: 'main/saveData',
            payload: {
                ...paramsObj
            }
        });
        if (res.success) {
            let data = res.data;
            if(data.errMsg){
                this.toast({color: 'danger', content: data.errMsg});
            }else{
                if(!!main.isNewAdd){ //保存新增
                    // console.log("refs:::",nodeRefs);
                    form.EmptyAllFormValue('bd_psndoc');
                    main.areaCodeList.map((item, index)=>{
                        cardTable.setTableData(item,{rows: []});
                    });
                }else{
                    await this.dispatch({
                        type: 'main/update',
                        payload: {
                            isEdit: false,
                            subTableEditable: false,
                            pk_psnjob: data.pk_psnjob
                        }
                    });
                    // cardTable.toggleCardTable(main.areaCodeList, false);
                    // cardTable.toggleCardTable('hi_psnjob', true);
                    action.btnAct.cancelButtonStatus();
                    form.cancel('bd_psndoc');
                    main.areaCodeList.map((item, index)=>{
                        cardTable.setStatus(item,'browse');
                    });
                    this.getSaveData(data.pk_psnjob)
                }
                this.toast({color: 'success', content: language['hi6007-000000']});
            }
        }
    }

    // 保存成功后调用数据
    getSaveData = async (pk_psnjob)=>{
        const { props, action } = this.comp;
        let { main, form, cardTable } = props;
        let res = await this.dispatch({
            type: 'main/getSaveData',
            payload: {
                func_type: 5,
                pk_org: main.pk_org,
                pk_psnjob: pk_psnjob
            }
        })
        if( res.success ){
            let data = res.data;
            if(!!data){
                let hi_psnorg_h = data.psnorgForm && data.psnorgForm.hi_psnorg_h;
                let hi_psnjob_h = data.psnjobForm && data.psnjobForm.hi_psnjob_h;
                //设置form 数据，相关人员只有bd_psndoc，下面两条备用
                form.setAllFormValue({
                    'bd_psndoc': data['psndocForm']['bd_psndoc'],
                    /*'hi_psnjob_h': data['psnjobForm']['hi_psnjob_h'],
                    'hi_psnorg_h': data['psnorgForm']['hi_psnorg_h']*/
                });
                // 设置表格数据
                // main.areaCodeList.map((item) => {
                //     if(data.certGrid && data.certGrid[item]) {
                //         cardTable.setTableData(item, data.certGrid[item], null, false);
                //     }
                //     else if(data.trainGrid && data.trainGrid[item], null, false) {
                //         cardTable.setTableData(item, data.trainGrid[item]);
                //     }
                //     else {
                //         cardTable.setTableData(item, {rows:[]}, null, false);
                //     }
                // });
                cardTable.toggleCardTable(main.areaCodeList, false);
                cardTable.toggleCardTable('hi_psnjob', true);
                this.dispatch({
                    type: 'main/update',
                    payload: {
                        hi_psnjob_h,
                        hi_psnorg_h: hi_psnorg_h,
                        pk_psndoc: hi_psnorg_h.rows[0].values.pk_psndoc.value
                    }
                })
                action.tableAct.setIsDisableUpload(true);
            }
        }
    }

    //设置编辑页面状态
    setEditCardStatus = async () =>{
        await this.dispatch({
            type: 'main/update',
            payload: {
                ui_state: 2
            }
        })
        this.editCard();
    }

    //编辑
    editCard = async () => {
        const {props, action} = this.comp;
        const {main, dispatch, form, cardTable, button} = props;
        await this.dispatch({
            type: 'main/update',
            payload: {
                isEdit: true,
                subTableEditable: true
            }
        })
        form.setFormStatus('bd_psndoc','edit');
        main.areaCodeList.map((item, index)=>{
            cardTable.setStatus(item,'edit');
        })
        action.btnAct.newButtonStatus();
    }

    //取消
    cancel = async () => {
        const { action, props } = this.comp;
        const { main, cardTable, form } = props;
        let { language, isSort, ui_state } = main;
        if( ui_state === 1 &&  !isSort){ //新增
            action.headerAct.backHomeList();
        }else{
            promptBox({
                color: "warning",
                title: language['hi6007-000008'],
                content: language['hi6007-000009'],
                beSureBtnClick: async () => {
                    if(isSort){     //排序状态取消时
                        action.headerAct.cancelAdjustSort();
                    }else{ 
                        await this.dispatch({
                            type: 'main/update',
                            payload: {
                                isEdit: false,
                                subTableEditable: false,
                                isSort: false
                            }
                        });
                        action.btnAct.cancelButtonStatus();
                        action.tableAct.setIsDisableUpload(true);
                        form.cancel('bd_psndoc');
                        !!main.areaCodeList.length && main.areaCodeList.map((item) => {
                            cardTable.setStatus(item, 'browse');
                        });
                    }
                }
            });
        }
    };

    //Form 编辑前事件
    formBeforeEvent = async (props, moduleId, key, value, data)=>{
        const { main, form, meta } = props;
        const { getAllFormValue, setFormItemsDisabled} = form;
        let metaData = meta.getMeta();
        let template = deepCopy(metaData);
        let res = await this.dispatch({
            type: 'main/formBeforeAction',
            payload: {
                areaCode: moduleId,
                func_type: 5,
                key: key,
                model: getAllFormValue(moduleId),
                pk_org: main.pk_org
            }
        })
        if( res.success ){
            let editable = res.data.editable;
            setFormItemsDisabled(moduleId, {
                [key]: !editable
            });
            if(res.data.refParam) {
                template[moduleId].items.map((item) => {
                    if(item.attrcode === key) {
                        /**
                         * 这里只修改了queryCondition的值，
                         * 没有修改queryCondition 的指针地址，
                         * */
                        //Object.assign(item['queryCondition'], res.data.refParam);
                        if (!item.queryCondition) item.queryCondition = {}
                        Object.assign(item.queryCondition, res.data.refParam)
                    }
                });
            }
            meta.setMeta(template);
        }
        return true;
    }

    // Form 编辑后事件
    formAfterEvent = async (props, moduleId, key, value, oldValue)=>{
        const { main, form } = props;
        const { getAllFormValue, setAllFormValue} = form;
        let res = await this.dispatch({
            type: 'main/formAfterAction',
            payload: {
                areaCode: moduleId,
                func_type: 5,
                key: key,
                model: getAllFormValue(moduleId),
                pk_org: main.pk_org
            }
        })
        if( res.success ){
            let formData = res.data.formData[moduleId];
            setAllFormValue({
                [key]: formData
            });
        }
        return true;
    }

    //子表编辑前事件
    



    // 点击子表左上侧三角展开事件
    /**
     * @param {*} props
     * @param {*} moduleId    模板ID
     * @param {*} isToggle    是否调用子表数据开关
     */
    headAngleToggle = async (props, moduleId, isToggle)=>{
        let { main, cardTable, editTable } = props;
        if( isToggle ){
            let res = await this.dispatch({
                type: 'main/getSubData',
                payload: {
                    areaCode: moduleId,
                    func_type: 5,
                    pk_psnjob: main.pk_psnjob,
                    pk_psndoc: main.pk_psndoc
                }
            })
            if(res.success && res.data && res.data[moduleId]) {
                if( !main.isCardForm ){ //区分cardTable和editTable, isCardForm 为true 是卡片界面 
                    editTable.setTableData(moduleId,{rows: res.data[moduleId].rows || []} )
                }else{
                    cardTable.setTableData(moduleId, {
                        rows: res.data[moduleId].rows || []
                    }, null, false);
                }
            }
        }
    }

    // cardTable 操作前事件
    handdleCardTableBefore = async (props, moduleId, key, value,  index, record, status)=>{
        const { main, meta, cardTable } = props;
        const { getAllData } = cardTable;
        let { pk_org, ui_state, sub_pkOrg } = main;
        let metaData = meta.getMeta();
        let template = deepCopy(metaData);
        let rowCount =  cardTable.getNumberOfRows(moduleId);
        let allTableData = getAllData(moduleId);
        let res = await this.dispatch({
            type: 'main/subTableBeforeAction',
            payload: {
                areaCode: moduleId,
                editType: ui_state,
                func_type: 5,
                key: key,
                model: allTableData,
                pk_org:  pk_org,
                rowCount:  rowCount, //当前子表一共有几行
                rowIndex: index //当前操作的是第几行
            }
        })
        if( res.success ){
            let editTable = res.data.editable;
            let param = res.data.refParam;

            cardTable.setEditableByIndex(moduleId, index, key, editTable);

            if(param) {
                template[moduleId].items.map((item) => {
                    if(item.attrcode === key) {
                        item['queryCondition'] = param;
                    }
                });
            }
            if( key === 'pk_dept' ){
                let param = {
                    "pk_org": !!sub_pkOrg ? sub_pkOrg : pk_org,
                    "TreeRefActionExt": "nccloud.web.hrhi.pub.sqlbuilder.DeptRefSqlBuilder",
                }
                template[moduleId].items.find(item => item.attrcode === key).queryCondition = function () {
                    return param
                };
            }
        }
        meta.setMeta(template);
        return true;
    }

    // cardTable 操作后事件
    subTableAfterAction = async (props, moduleId, key, value, changedRows, index, record, type, method)=>{
        const { main, cardTable } = props;
        const { getAllData } = cardTable;
        let { pk_org } = main;
        let allTableData = getAllData(moduleId);
        let res = await this.dispatch({
            type: 'main/subTableAfterAction',
            payload: {
                areaCode: moduleId,
                func_type: 5,
                key: key,
                model: allTableData,
                oldValue: changedRows[0].oldvalue.value,
                pk_org: pk_org
            }
        })
        if( res.success ){
            
            // 拿到该行设置的值
            if(res.data.gridData[moduleId]) {
                allTableData[index] = res.data.gridData[moduleId].rows[0];
                cardTable.setTableData(moduleId, {
                    rows: allTableData
                });
                if( key === 'pk_org' ){
                    let sub_pkOrg = allTableData[0].values.pk_org.value;
                    this.dispatch({
                        type: 'main/update',
                        payload: {
                            sub_pkOrg: sub_pkOrg
                        }
                    })
                }
            }
            // 提示错误信息
            if(res.data.errMsg) {
                this.toast({
                    color: 'danger',
                    content: res.data.errMsg
                });
            }
        }
        return true;
    }
}